package cqrtplm.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.service.FlowControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;

import java.math.BigInteger;

/**
 * 发起者角色分支判断监听器
 * 根据发起者角色判断流程分支，清空不匹配分支的执行人
 * @author 张宇
 */
@Slf4j
@CustomListener(category = "润通", description = "发起者角色分支判断")
public class RTInitiatorRoleBranchListener implements ExecutionListener {

    @CustomListenerField(description = "节点ID", defaultValue = "", required = true)
    private FixedValue nodeId;

    @CustomListenerField(description = "角色条件表达式", defaultValue = "", required = true)
    private FixedValue roleCondition;

    @Override
    public void notify(DelegateExecution execution) {
        long start = System.currentTimeMillis();
        String workFlowContainerId = execution.getProcessInstanceBusinessKey();
        log.info("----------润通----发起者角色分支判断------开始------workFlowContainerId:{}----->>>", workFlowContainerId);

        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = execution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }

        try {
            // 获取发起者信息
            UserDO initiator = TyAccountContext.getUser();
            if (initiator == null) {
                log.warn("无法获取发起者信息，跳过角色分支判断");
                return;
            }

            String finalWorkFlowContainerId = workFlowContainerId;
            FlowControlService flowControlService = SpringUtil.getBean(FlowControlService.class);

            // 调用服务方法进行角色分支判断
            String nodeIdValue = nodeId != null ? nodeId.getExpressionText() : null;
            String roleConditionValue = roleCondition != null ? roleCondition.getExpressionText() : null;
            
            flowControlService.checkInitiatorRoleBranch(
                new BigInteger(finalWorkFlowContainerId),
                nodeIdValue,
                roleConditionValue
            );
        } catch (Exception e) {
            log.error("发起者角色分支判断处理失败", e);
            throw new RuntimeException("发起者角色分支判断处理失败", e);
        }
        
        log.info("----------润通----发起者角色分支判断,耗时：{}---->>>", System.currentTimeMillis() - start);
    }
}

